package com.example.linearlayoutdemo.bindservice;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

public class GpsService extends Service {
    private GpsDataCallback callback; // 回调接口引用
    private LocationManager locationManager;

    public interface GpsDataCallback {
        void onGpsDataUpdated(double latitude, double longitude, long timestamp);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        initLocationListener(); // 初始化监听器（仅创建对象，不注册）
    }

    // 绑定 Service 时调用，返回 Binder 实例
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new GpsBinder();
    }

    // Binder 内部类：用于 Activity 获取 Service 引用
    public class GpsBinder extends Binder {
        public GpsService getService() {
            return GpsService.this;
        }
    }

    // 注册回调（Activity 绑定后调用）
    public void setGpsCallback(GpsDataCallback callback) {
        this.callback = callback;
    }

    // 模拟 GPS 数据更新（实际中由 LocationListener 触发）
    private void updateGpsData(double lat, double lon) {
        if (callback != null) {
            // 直接调用回调，传递数据（无序列化）
            callback.onGpsDataUpdated(lat, lon, System.currentTimeMillis());
        }
    }

    // 初始化定位监听（简化示例）
    private void initLocationListener() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.e("GpsService", "缺少 GPS 定位权限");
            return;
        }
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                100, // 最短更新间隔（毫秒）
                0,   // 最短更新距离（米）
                location -> updateGpsData(location.getLatitude(), location.getLongitude())
        );
    }
    private void stopGpsListening() {
        if (locationManager != null) {
            locationManager.removeUpdates(new LocationListener() {
                @Override public void onLocationChanged(Location location) {}
                @Override public void onStatusChanged(String provider, int status, Bundle extras) {}
                @Override public void onProviderEnabled(String provider) {}
                @Override public void onProviderDisabled(String provider) {}
            });
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // Service 销毁时强制停止定位，释放资源
        stopGpsListening();
        Log.d("tag", "Service 销毁，已停止定位");
    }
}